//
//  RdbWebViewController.swift
//  rdb-led-banner
//
//  Created by radiobox3 on 2025/4/22.
//

import UIKit
import SnapKit
import WebKit

class RdbWebViewController: BaseViewController,WKNavigationDelegate {

    var url: URL?
    var isLocal: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.showBackButton = true
        self.view.addSubview(webView)
        self.view.backgroundColor = RdbColor.background.main.color
        self.webView.snp.makeConstraints {
            $0.edges.equalTo(UIEdgeInsets(top: UIDevice.navigationBarHeight(), left: 0, bottom: 0, right: 0))
        }
        self.loadData()
    }
    
    convenience init(url: URL?) {
        self.init()
        self.isLocal = false
        self.url = url
    }
    
    convenience init(forResource name: String?, withExtension ext: String?) {
        self.init()
        self.isLocal = true
        self.url = Bundle.main.url(forResource: name, withExtension: ext)
    }
    
    func loadData() {
        if let fileURL = self.url {
            if self.isLocal {
                self.webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL)
            } else {
                self.webView.load(URLRequest(url: fileURL))
            }
        }
    }
    
    /**
     func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
         webView.evaluateJavaScript("document.getElementsByTagName('body')[0].style.background='#121212'")
         webView.evaluateJavaScript("document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'white'")
     }
     */
    
    
    private lazy var webView: WKWebView = {
        let webView = WKWebView()
        webView.navigationDelegate = self
        webView.backgroundColor = RdbColor.background.main.color
        return webView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit{
        webView.navigationDelegate = nil
        webView.stopLoading()
    }

}
